import traceback
from pyim import handler
from pyim import processor
import threadpool
import queue


class LocalQueue(processor.Processor):
    def read_packet(self):
        while True:
            try:
                task = threadpool.WorkRequest(callable_=handler.handle,
                                              args=self.get())
                self.thread_pool.putRequest(task)
            except Exception:
                traceback.print_exc()

    def __init__(self, num_workers=1, request_queue_size=100):
        self.thread_pool = threadpool.ThreadPool(num_workers + 1)
        self.thread_pool.putRequest(threadpool.WorkRequest(callable_=self.read_packet))
        self.queue = queue.Queue(request_queue_size)

    def put(self, connection, packet, *args, **kwargs):
        try:
            self.queue.put_nowait((connection, packet))
        except queue.Full:
            raise processor.Busy

    def get(self, *args, **kwargs):
        return self.queue.get()
